#!/usr/bin/env python3
"""
初始化IP白名单脚本
在Redis中设置默认的IP白名单，包含本地和常见内网IP
"""

import asyncio
import json
from datetime import datetime
import sys
import os

# 添加项目根目录到Python路径
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from app.core.redis_client import redis_manager

# 默认IP白名单
DEFAULT_IPS = [
    {
        "ip": "127.0.0.1",
        "description": "本地回环地址",
        "added_at": datetime.now().isoformat()
    },
    {
        "ip": "localhost",
        "description": "本地主机名",
        "added_at": datetime.now().isoformat()
    },
    {
        "ip": "192.168.0.0/16",
        "description": "私有网络A类地址段",
        "added_at": datetime.now().isoformat()
    },
    {
        "ip": "10.0.0.0/8",
        "description": "私有网络B类地址段",
        "added_at": datetime.now().isoformat()
    },
    {
        "ip": "172.16.0.0/12",
        "description": "私有网络C类地址段",
        "added_at": datetime.now().isoformat()
    }
]

async def init_ip_whitelist():
    """初始化IP白名单"""
    try:
        # 检查是否已存在白名单
        existing_data = await redis_manager.get_json("settings:ip_whitelist")
        
        if existing_data:
            print("IP白名单已存在，跳过初始化")
            print(f"当前白名单包含 {len(existing_data.get('ips', []))} 个IP")
            return
        
        # 创建默认白名单
        whitelist_data = {
            "ips": DEFAULT_IPS,
            "created_at": datetime.now().isoformat(),
            "version": "1.0"
        }
        
        # 保存到Redis
        success = await redis_manager.set_json("settings:ip_whitelist", whitelist_data)
        
        if success:
            print("✅ IP白名单初始化成功")
            print(f"已添加 {len(DEFAULT_IPS)} 个默认IP:")
            for ip_entry in DEFAULT_IPS:
                print(f"  - {ip_entry['ip']} ({ip_entry['description']})")
        else:
            print("❌ IP白名单初始化失败")
            
    except Exception as e:
        print(f"❌ 初始化IP白名单时发生错误: {e}")

async def main():
    """主函数"""
    print("开始初始化IP白名单...")
    await init_ip_whitelist()
    print("初始化完成")

if __name__ == "__main__":
    asyncio.run(main())
